package com.csy.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csy.admin.entity.SysMenu;
import com.csy.admin.mapper.SysMenuMapper;
import com.csy.admin.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author csy
 * @since 2018-09-11
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**
     * 根据角色获取用户权限
     * @param roleId
     * @return
     */
    @Override
    public List<SysMenu> findPermissionByRole(Long roleId) {
        List<SysMenu> menuList = sysMenuMapper.selectPermissionByRole(roleId);
        return menuList;
    }


    /**
     * 获取用户菜单
     * @param userId 用户id
     * @return
     */
    @Override
    public List<SysMenu> getUserMenuList(Long userId) {
        List<SysMenu> menuRoot = queryListParentId(userId,0L);
        getMenuTreeList(menuRoot,userId);
        return menuRoot;
    }


    /**
     * 根据父节点获取菜单
     * @param userId 用户id
     * @param parentId 父菜单id
     * @return 菜单列表
     */
    private List<SysMenu> queryListParentId(Long userId,Long parentId) {
        List<SysMenu> menuList = sysMenuMapper.queryListParentId(userId,parentId);
        return menuList;
    }

    /**
     * 递归获取菜单
     * @param menuList
     * @param userId
     * @return
     */
    private List<SysMenu> getMenuTreeList(List<SysMenu> menuList,Long userId){
        List<SysMenu> subMenuList = new ArrayList<>();
        for(SysMenu menu : menuList){
            menu.setList(getMenuTreeList(queryListParentId(userId,menu.getMenuId()),userId));
            subMenuList.add(menu);
        }
        return subMenuList;
    }

    /**
     * 获取菜单树(添加，修改菜单时选择上级菜单时用)
     * @return
     */
    @Override
    public List<SysMenu> queryNotButtonList() {
        return sysMenuMapper.queryNotButtonList();
    }

}
